package cn.bdqn.dao.impl;

import cn.bdqn.dao.BaseDao;
import cn.bdqn.dao.PetOwnerDao;
import cn.bdqn.entity.Pet;
import cn.bdqn.entity.PetOwner;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class PetOwnerDaoImpl extends BaseDao implements PetOwnerDao {


    @Override
    public List<PetOwner> queryPetOwner() throws Exception {
        // 获取连接信息
        Connection connection = getConnection();
        //  查询SQL
        String querySql = "select * from petowner;";
        PreparedStatement pstmt = connection.prepareStatement(querySql);
        // 执行SQL
        ResultSet result = pstmt.executeQuery();
        // 创建宠物list 保存数据库里面的数据
        List<PetOwner> petOwnerList =  new ArrayList<PetOwner>();
        while(result.next()){
            // 创建一个空的宠物对象，保存数据
            PetOwner petOwner = new PetOwner();
            // 渲染数据   数据库的数据要与java实体类数据对齐
            petOwner.setId(result.getInt("id"));
            petOwner.setName(result.getString("name"));
            petOwner.setPassword(result.getString("password"));
            petOwner.setMoney(result.getInt("money"));
            // 讲pet对象存入List中
            petOwnerList.add(petOwner);
        }

        return petOwnerList;
    }

    @Override
    public PetOwner queryPetOwnerByLogin(String name, String password) throws Exception {
        // 获取连接信息
        Connection connection = getConnection();
        //  查询SQL
        String querySql = "select * from petowner where `name`=? and `password`=?;";
        PreparedStatement pstmt = connection.prepareStatement(querySql);
        pstmt.setString(1, name);
        pstmt.setString(2, password);
        // 执行SQL
        ResultSet result = pstmt.executeQuery();
        // 有结果登录成功，没有结果登录失败
        if (result.next()){
            // 创建一个空的宠物对象，保存数据
            PetOwner petOwner = new PetOwner();
            // 渲染数据   数据库的数据要与java实体类数据对齐
            petOwner.setId(result.getInt("id"));
            petOwner.setName(result.getString("name"));
            petOwner.setPassword(result.getString("password"));
            petOwner.setMoney(result.getInt("money"));
            return petOwner;
        }else{
            return null;
        }
    }


}
